package edu.uwlax.cs.oayonlinestore.client.gui.stock;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Widget;

import edu.uwlax.cs.oayonlinestore.client.OnlinestoreRService;
import edu.uwlax.cs.oayonlinestore.client.gui.Store;
import edu.uwlax.cs.oayonlinestore.client.utils.DefaultAsyncCallback;
import edu.uwlax.cs.oayonlinestore.client.utils.DekoTable;
import edu.uwlax.cs.oayonlinestore.client.utils.SwitchPage;
import edu.uwlax.cs.oayonlinestore.client.utils.Title;
import edu.uwlax.cs.oayonlinestore.client.utils.TitlePage;
import edu.uwlax.cs.oayonlinestore.vo.ProductDetailsVO;

public class PageStockEditItemList extends TitlePage {
	int subID;

	private class EditItemTable extends DekoTable {
		Button add, delete;

		public EditItemTable() {
			super();
			String anchor = Store.getFrame().getStockEditItem().getAnchor(
					subID, 0);
			Button add = new Button("Add Item");
			add.addClickListener(new SwitchPage(anchor));
			addTitle("Brand");
			addTitle("Product");
			addTitle("Available");
			addTitle("");
			addTitleWidget(add);
		}

		public void addItem(ProductDetailsVO item) {
			String anchor = Store.getFrame().getStockEditItem().getAnchor(
					subID, item.getId());
			Hyperlink edit = new Hyperlink("Edit", anchor);
			AddRow r = addRow();
			r.add(item.getBrand());
			r.add(item.getName());
			r.add(item.getInStockCount());
			r.add(edit);
			r.add(delete = new Button("Delete"));
			delete.setWidth("165");
			delete.addClickListener(new ButtonClickListener(item));
		}

		public class ButtonClickListener implements ClickListener {
			ProductDetailsVO co = null;

			public ButtonClickListener(ProductDetailsVO c) {
				co = c;
			}

			public void onClick(Widget arg0) {

				OnlinestoreRService.Util.getInstance().disableProduct(
						co.getId(), new DoneAddAsycHandler());
			}
		}

		public class DoneAddAsycHandler extends DefaultAsyncCallback {

			public void onSuccess(Object o) {
				onShow(subID);
			}
		}
	}

	EditItemTable table;// = new EditItemTable();

	protected void create() {
		setTitle("Items");

	}

	public boolean onShow(int param) {
		subID = param;
		removeAll();
		add(new Title("Items"));
		add(table = new EditItemTable());
		OnlinestoreRService.Util.getInstance().getProductDetailList(subID,
				getAsyncHandler());
		return true;
	}

	protected void onDataArrived(Object o) {
		ProductDetailsVO[] items = (ProductDetailsVO[]) o;
		for (int i = 0; i < items.length; i++)
			table.addItem(items[i]);

	}

	public String getID() {
		return "ItemList";
	}
}
